package com.eurasia.assignment.service;

import com.eurasia.assignment.domain.Class;
import com.eurasia.assignment.infrastructure.repository.ClassRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 班级服务类
 * 提供班级相关的业务逻辑
 */
@Service
public class ClassService {

    private final ClassRepository classRepository;

    @Autowired
    public ClassService(ClassRepository classRepository) {
        this.classRepository = classRepository;
    }

    /**
     * 创建并自动保存新班级
     */
    @Transactional
    public Class createClass(String className, String grade, String major, String tutor) {
        Class newClass = Class.create(className, grade, major, tutor);
        return classRepository.save(newClass);
    }

    /**
     * 创建并保存一个完整的班级对象
     */
    @Transactional
    public Class createClassComplete(Class classObj) {
        return classRepository.save(classObj);
    }

    /**
     * 更新班级信息并自动保存
     */
    @Transactional
    public Class updateClass(Long id, String className, String grade, String major, 
                           String tutor, Integer studentCount, String remark) {
        Optional<Class> existingClass = classRepository.findById(id);
        
        if (existingClass.isEmpty()) {
            throw new RuntimeException("班级不存在，ID: " + id);
        }
        
        Class classToUpdate = existingClass.get();
        classToUpdate.setClassName(className);
        classToUpdate.setGrade(grade);
        classToUpdate.setMajor(major);
        classToUpdate.setTutor(tutor);
        classToUpdate.setStudentCount(studentCount);
        classToUpdate.setRemark(remark);
        
        return classRepository.save(classToUpdate);
    }

    /**
     * 根据ID获取班级
     */
    public Optional<Class> getClassById(Long id) {
        return classRepository.findById(id);
    }

    /**
     * 获取所有班级
     */
    public List<Class> getAllClasses() {
        return classRepository.findAll();
    }

    /**
     * 根据专业获取班级
     */
    public List<Class> getClassesByMajor(String major) {
        return classRepository.findByMajor(major);
    }

    /**
     * 根据年级获取班级
     */
    public List<Class> getClassesByGrade(String grade) {
        return classRepository.findByGrade(grade);
    }

    /**
     * 根据班级名称查找班级
     */
    public Class getClassByName(String className) {
        return classRepository.findByClassName(className);
    }

    /**
     * 批量保存班级
     */
    @Transactional
    public List<Class> saveAllClasses(List<Class> classes) {
        return classRepository.saveAll(classes);
    }

    /**
     * 删除班级
     */
    @Transactional
    public void deleteClass(Long id) {
        classRepository.deleteById(id);
    }
} 